<template>
  <NuxtLayout name="admin" menuActive="/admin/teacher">
    <div class="card">
      <el-page-header @back="useRouter().go(-1)">
        <template #content>
          <el-input v-model="listForm.keyword" placeholder="请输入教师名称">
            <template #append>
              <el-button :icon="Search" @click="searchFn"></el-button>
            </template>
          </el-input>
        </template>
        <template #extra>
          <el-button @click="addFn">添加教师</el-button>
        </template>
      </el-page-header>
      <div style="height: 18px;"></div>
      <el-table :data="tableData" border show-overflow-tooltip>
        <el-table-column prop="name" label="教师名称" width="100" />
        <el-table-column prop="phoneNo" label="电话号码" width="120" />
        <el-table-column prop="idNumber" label="身份证号码" />
        <el-table-column prop="entryTime" label="入职时间" />
        <el-table-column label="主讲科目">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.subjects" :key="item.id">{{ item.name }}{{ index + 1 <
              scope.row.subjects.length ? '，' : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="教师头像" width="128">
          <template #default="scope">
            <el-image style="width: 100px;height: 100px;" :src="scope.row.portrait"
              :preview-src-list="[scope.row.portrait]" preview-teleported fit="cover"
              v-show="scope.row.portrait" />
          </template>
        </el-table-column>
        <el-table-column label="学历证书" width="128">
          <template #default="scope">
            <el-image style="width: 100px;height: 100px;" :src="scope.row.educationCert"
              :preview-src-list="[scope.row.educationCert]" preview-teleported fit="cover"
              v-show="scope.row.educationCert" />
          </template>
        </el-table-column>
        <el-table-column label="资格证书" width="128">
          <template #default="scope">
            <el-image style="width: 100px;height: 100px;" :src="scope.row.qualificationCert"
              :preview-src-list="[scope.row.qualificationCert]" preview-teleported fit="cover"
              v-show="scope.row.qualificationCert" />
          </template>
        </el-table-column>
        <el-table-column label="职称证书" width="128">
          <template #default="scope">
            <el-image style="width: 100px;height: 100px;" :src="scope.row.professionalCert"
              :preview-src-list="[scope.row.professionalCert]" preview-teleported fit="cover"
              v-show="scope.row.professionalCert" />
          </template>
        </el-table-column>
        <el-table-column prop="brief" label="简介" />
        <el-table-column label="操作" fixed="right" width="135">
          <template #default="scope">
            <el-button type="success" size="small" @click="editFn(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="delFn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card_pagin">
        <el-pagination background layout="prev, pager, next, total" :total="total" :page-size="listForm.pageSize"
          @change="pageChangeFn" />
      </div>
    </div>
    <MyForm :visible="formVisible" :forms="forms" :title="formTitle" @pick="formPickFn" />
  </NuxtLayout>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { teacherList, teacherAdd, teacherUpdate, teacherDelete } from '~/server/api';
import { formatTime } from '~/utils/utils'
import MyForm from './form';
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
useSeoMeta({
  title: "技考邦_教师管理",
  keywords: "技考邦,教师管理",
  description: "技考邦，教师管理。",
  ogTitle: "技考邦_教师管理",
  ogDescription: "技考邦，教师管理。",
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
})
const formVisible = ref(false)
const formTitle = ref('')
const forms = ref({
  id: '',
  name: '',
  phoneNo: '',
  idNumber: '',
  education: '',
  entryTime: '',
  brief: '',
  subjectIds: null,
  educationCert: '',
  professionalCert: '',
  qualificationCert: '',
  portrait: ''
})
const listForm = ref({
  pageNum: 1,
  pageSize: 20,
  keyword: ''
})
const tableData = ref([])
const total = ref(0)
const getList = async () => {
  const { data: listRes } = await useAsyncData('teacherList', () => useServerRequest(teacherList, {
    method: 'post',
    body: JSON.stringify(listForm.value)
  }))
  if (listRes.value && listRes.value.errno === 0 && listRes.value.result && listRes.value.result.list.length > 0) {
    tableData.value = listRes.value.result.list;
    total.value = listRes.value.result.total;
  }
}
getList()
// 搜索
const searchFn = () => {
  listForm.value.pageNum = 1;
  getList()
}
// 分页
const pageChangeFn = (val) => {
  listForm.value.pageNum = val;
  getList()
}
// 添加
const addFn = () => {
  forms.value.id = '';
  forms.value.name = '';
  forms.value.phoneNo = '';
  forms.value.idNumber = '';
  forms.value.education = '';
  forms.value.entryTime = formatTime(new Date().getTime());
  forms.value.brief = '';
  forms.value.subjectIds = [];
  forms.value.educationCert = '';
  forms.value.professionalCert = '';
  forms.value.qualificationCert = '';
  forms.value.portrait = '';
  formTitle.value = '添加教师';
  formVisible.value = true;
}
// 编辑
const editFn = (val) => {
  forms.value.id = val.id;
  forms.value.name = val.name;
  forms.value.phoneNo = val.phoneNo;
  forms.value.idNumber = val.idNumber;
  forms.value.education = val.education;
  forms.value.entryTime = val.entryTime;
  forms.value.brief = val.brief;
  forms.value.subjectIds = val.subjectIds;
  forms.value.educationCert = val.educationCert;
  forms.value.professionalCert = val.professionalCert;
  forms.value.qualificationCert = val.qualificationCert;
  forms.value.portrait = val.portrait;
  formTitle.value = '编辑教师';
  formVisible.value = true;
}
// 删除
const delFn = (val) => {
  ElMessageBox.confirm('是否删除当前数据', {
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  }).then(async () => {
    let delRes = await useServerRequest(teacherDelete, {
      method: 'post',
      body: JSON.stringify({
        id: val.id
      })
    })
    if (delRes.errno === 0) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      getList()
      return false;
    }
  }).catch(() => {})
}
// 取消 确认
const formPickFn = async (e) => {
  if (e.form) {
    if (e.form.name == '') {
      ElMessage({
        message: '请输入教师名称',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.phoneNo != '' && !/^1[3456789]\d{9}$/.test(e.form.phoneNo)) {
      ElMessage({
        message: '电话号码有误',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.idNumber != '' && !/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/.test(e.form.idNumber)) {
      ElMessage({
        message: '身份证号码有误',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    const loading = ElLoading.service({ text: '请求中...', target: document.querySelector('.el-dialog') })
    let url = e.form.id ? teacherUpdate : teacherAdd;
    let teacherRes = await useServerRequest(url, {
      method: 'post',
      body: JSON.stringify(e.form)
    })
    if (teacherRes.errno === 0) {
      ElMessage({
        message: e.form.id ? '修改成功' : '添加成功',
        type: 'success'
      })
      getList()
      formVisible.value = e.visible;
    }
    loading.close()
    return false;
  }
  formVisible.value = e.visible;
}
</script>

<style lang="less" scoped>
.card {
  background: #FFFFFF;
  border-radius: 10px;
  border: 1px solid #EEEEEE;
  padding: 35px 25px;

  &_pagin {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }
}
</style>